package org.nature.framework.util;

import java.util.ArrayList;
import java.util.List;

import org.nature.framework.bean.RedisHostBean;
import org.nature.framework.helper.ConfigHelper;

import redis.clients.jedis.JedisPoolConfig;
import redis.clients.jedis.JedisShardInfo;
import redis.clients.jedis.ShardedJedis;
import redis.clients.jedis.ShardedJedisPool;
import redis.clients.util.Hashing;
import redis.clients.util.Sharded;

public class JedisUtil {
	public static ShardedJedisPool pool;
	static {//TODO 切片/集群
		JedisPoolConfig config = new JedisPoolConfig();
		config.setMaxIdle(ConfigHelper.getRedisMaxIdle());
		config.setMinIdle(ConfigHelper.getRedisMinIdle());
		config.setMaxWaitMillis(ConfigHelper.getRedisMaxWaitMillis());
		config.setMaxTotal(ConfigHelper.getRedisMaxTotal());
		List<JedisShardInfo> jdsInfoList = new ArrayList<JedisShardInfo>();
		List<RedisHostBean> redisHostPortMap = ConfigHelper.getRedisHostPortMap();
		for (RedisHostBean redisHostBean : redisHostPortMap) {
			JedisShardInfo infoA = new JedisShardInfo(redisHostBean.getHost(), redisHostBean.getPort());
			infoA.setPassword(redisHostBean.getPassword());
			jdsInfoList.add(infoA);
		}
		pool = new ShardedJedisPool(config, jdsInfoList, Hashing.MURMUR_HASH, Sharded.DEFAULT_KEY_TAG_PATTERN);
	}

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		ShardedJedis jds = null;
		try {
			jds = pool.getResource();
			long setnx = jds.hset("xx", "a", "ab");
			System.out.println(setnx);
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			jds.close();
		}
	}

}
